/**
 * @description  维度（资产配置）
 * @author zht
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Row, Col, Spin, Tooltip } from 'antd';
import { SecondHeaderC, DATA_ENTRY, AdvancedSearch, FirstHeaderC, NoQueryC, TableC, SunEchartsC } from '../../../comps';
import upRed from '../../../assets/commom/up_arrow_red.png';
import downGreen from '../../../assets/commom/down_arrow_green.png';
import ChartPie from './chartPie';
import accounting from 'accounting';
import _ from 'lodash';
import myStyle from './index.less';
import { getColumnIntoWidth } from '../../../utils/utils';

@Form.create()
class dimensionality extends PureComponent {
  constructor() {
    super();
    this.state = {
      assetType: 'BOND', // 资产类别
      dimension: 'RATING', // 维度
      columns: [], // 表格列
      dataSource: [], // 表格数据
      currentPage: 1, // 当前页
      numInPage: 1000, // 每页条数
      dimensionClass: [], // 维度下拉列表
      assetClass: [], // 资产下拉类别
      dimensionDef: '', // 维度默认值
      assetTypeDef: 'BOND',
    };
  }

  componentDidMount() {
    const { args, dispatch } = this.props;
    const {
      globalM: {
        dataDictionary: { ASSET_ALLOCATION = [], ASSET_ALLOCATION_BOND = [] },
      },
    } = this.props;
    const assetClass = this.onChangeassetClass(ASSET_ALLOCATION);
    this.setState({
      assetClass,
    });
    // 获取维度字典
    const dimensionClass = this.onChangedimensionClass(ASSET_ALLOCATION_BOND);
    this.setState({
      dimensionClass,
      dimensionDef: dimensionClass[0]?.value,
    });
    this.getData(args);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { args } = nextProps;
    if (args.portfolioCode || args.portfolioCodeList) {
      if (JSON.stringify(args) !== JSON.stringify(this.props.args)) {
        this.getData(args);
      }
    }
  }

  // 获取数据
  getData = (args) => {
    const { currentPage, numInPage, assetType, dimension } = this.state;
    const { type } = this.props;
    const portfolioCode = args.portfolioCode
      ? {
          portfolioCode: args.portfolioCode,
        }
      : {
          portfolioCodeList: JSON.stringify(args.portfolioCodeList),
        };
    const datas = {
      ...portfolioCode,
      timeRange: args.timeRange,
      beginDate: args.beginDate,
      endDate: args.endDate,
      needPenetrate: args.needPenetrate,
      zqfz: args.zqfz,
    };
    this.props.dispatch({
      type: 'assetAllocationM/queryDimensionData',
      payload: {
        ...datas,
        assetType,
        dimension,
        currentPage,
        numInPage,
      },
      callback: (data) => {
        if (data && data.dataSource.length && data.columns.length) {
          data.columns.map((item) => {
            if (item.key == 'holdAmount') {
              item.title = type == 1 ? `${item.title}（元）` : `${item.title}（亿元）`;
            }
            if (item.key == 'holdAmountChange') {
              item.title = type == 1 ? `${item.title}（元）` : `${item.title}（万元）`;
            }
          });
          data.dataSource.map((item) => {
            if (type == 2) {
              item.holdAmount = parseFloat((item.holdAmount || 0) / 100000000);
            }
          });
          const pieData = this.queryPieData(data.dataSource);
          const columnss = this.changeColumns(getColumnIntoWidth(data.columns, data.dataSource));
          const dataSources = this.changeDataSource(data.dataSource);
          this.setState({
            columns: columnss,
            dataSource: dataSources,
            pieData,
          });
        } else {
          this.setState({
            columns: [],
            dataSource: [],
            pieData: [],
          });
        }
      },
    });
  };

  // 获取饼图数据
  queryPieData = (dataSource) => {
    const pieData = [];
    dataSource.map((item) => {
      const { dimension, holdRatio } = item;
      if (dimension !== '总计') {
        pieData.push({
          name: dimension,
          value: holdRatio?.toFixed(4),
        });
      }
    });
    return pieData;
  };

  // 改变表格钱数据样式
  changMoney = (data) => {
    if (data === null || data === undefined) {
      return '--';
    } else {
      if (this.props.type == 2) data = parseFloat(Number(data) / 10000);
      return accounting.formatNumber(Number(data), 2);
    }
  };

  // 改变表格利率数据样式
  changRate = (data) => {
    if (data === null || data === undefined) {
      return '--';
    } else {
      // NaN: Not a Number
      // isNaN()的缺点就在于 null、空格以及空串会被按照0来处理
      if (isNaN(data)) {
        return data;
      } else {
        return `${(Number(data) * 100).toFixed(2)}%`;
      }
    }
  };

  // 优化表格数据
  changeDataSource = (dataSource) => {
    const newDataSource = _.cloneDeep(dataSource);
    newDataSource.forEach((value) => {
      if (value.holdAmountChangeFlg == 'up') {
        value.holdAmountChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellUp}>{this.changMoney(value.holdAmountChange)}</span>
            <img style={{ width: '16px', height: '20px' }} src={upRed}></img>
          </div>
        );
      } else if (value.holdAmountChangeFlg == 'down') {
        value.holdAmountChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellDown}>{this.changMoney(value.holdAmountChange)}</span> <img style={{ width: '16px', height: '20px' }} src={downGreen}></img>
          </div>
        );
      } else {
        value.holdAmountChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cell}>{this.changMoney(value.holdAmountChange)} -</span>
          </div>
        );
      }
      if (value.holdRatioChangeFlg == 'up') {
        value.holdRatioChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellUp}>{this.changRate(value.holdRatioChange)}</span> <img style={{ width: '16px', height: '20px' }} src={upRed}></img>
          </div>
        );
      } else if (value.holdRatioChangeFlg == 'down') {
        value.holdRatioChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellDown}>{this.changRate(value.holdRatioChange)}</span> <img style={{ width: '16px', height: '20px' }} src={downGreen}></img>
          </div>
        );
      } else {
        value.holdRatioChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cell}>{this.changRate(value.holdRatioChange)} -</span>
          </div>
        );
      }
    });
    const compare = (key) => {
      return (obj1, obj2) => {
        // 降序
        const val1 = obj1[key];
        const val2 = obj2[key];
        if (val1 < val2) {
          return 1;
        } else if (val1 > val2) {
          return -1;
        } else {
          return 0;
        }
      };
    };
    const data = newDataSource[newDataSource.length - 1];
    newDataSource.pop();
    newDataSource.sort(compare('holdRatio'));
    newDataSource.push(data);
    return newDataSource;
  };

  // 优化表格样式
  changeColumns = (columns) => {
    columns.forEach((value, index) => {
      if (value.key == 'dimension') {
        value.width = '70px';
      }
      if (value.key == 'holdRatio') {
        value.type = 'rate';
        value.width = '80px';
      }
      if (value.key == 'holdAmount') {
        value.type = 'money';
        // value['width'] = '150px'
      }
      if (value.key == 'holdAmountChange') {
        value.align = 'right';
        value.width = '167px';
        // value['width'] = '167px'
      }

      if (value.key == 'holdRatioChange') {
        value.title = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span>{value.title}</span>
            <Tooltip title={<div>该维度期初市值占比与期末市值占比之差</div>}>
              <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
            </Tooltip>
          </div>
        );
        // value['width'] = '167px'
      }
    });

    return columns;
  };

  // 资产类别下拉数据转换
  onChangeassetClass = (e) => {
    const assetClass = [];
    if (e && e.length) {
      e.map((item) => {
        assetClass.push({
          title: item.value,
          value: item.code,
        });
      });
      return assetClass;
    }
  };

  // 维度下拉数据转换
  onChangedimensionClass = (e) => {
    const dimensionClass = [];
    if (e && e.length) {
      e.map((item) => {
        dimensionClass.push({
          title: item.value,
          value: item.code,
        });
      });
      return dimensionClass;
    }
  };

  // 资产下拉事件
  assetChange = (e) => {
    if (e == 'BOND') {
      const {
        globalM: {
          dataDictionary: { ASSET_ALLOCATION_BOND = [] },
        },
      } = this.props;
      const dimensionClass = this.onChangedimensionClass(ASSET_ALLOCATION_BOND);
      this.setState({
        dimensionClass,
      });
      if (dimensionClass.length) this.state.dimensionSelect.setSelect(dimensionClass[0].value);
    } else if (e == 'FUND') {
      const {
        globalM: {
          dataDictionary: { ASSET_ALLOCATION_FUND = [] },
        },
      } = this.props;
      const dimensionClass = this.onChangedimensionClass(ASSET_ALLOCATION_FUND);
      this.setState({
        dimensionClass,
      });
      if (dimensionClass.length) this.state.dimensionSelect.setSelect(dimensionClass[0].value);
    } else {
      const {
        globalM: {
          dataDictionary: { ASSET_ALLOCATION_STOCK = [] },
        },
      } = this.props;
      const dimensionClass = this.onChangedimensionClass(ASSET_ALLOCATION_STOCK);
      this.setState({
        dimensionClass,
      });
      if (dimensionClass.length) this.state.dimensionSelect.setSelect(dimensionClass[0].value);
    }
  };

  // 搜索事件
  searchData = (e) => {
    if (e.assetType && e.dimension) {
      this.setState(
        {
          assetType: e.assetType,
          dimension: e.dimension,
        },
        () => this.getData(this.props.args),
      );
    } else {
      message.warning('请填写完整的查询条件”');
    }
  };

  render() {
    const { pieData, columns, dataSource, assetClass, dimensionClass, dimensionDef, assetTypeDef } = this.state;
    const { type } = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'assetType',
          title: '资产类别',
          type: DATA_ENTRY.SELECT,
          dataSource: assetClass,
          initialValue: assetTypeDef,
          onChange: (e) => this.assetChange(e),
        },
        {
          dataIndex: 'dimension',
          title: '维度',
          type: DATA_ENTRY.SELECT,
          dataSource: dimensionClass,
          initialValue: dimensionDef,
          onRef: (ref) => {
            this.state.dimensionSelect = ref;
          },
        },
      ],
      onQuery: (e) => {
        this.searchData(e);
      },
      onClear: () => {
        this.setState({
          assetTypeDef: 'BOND',
        });
        const {
          globalM: {
            dataDictionary: { ASSET_ALLOCATION_BOND = [] },
          },
        } = this.props;
        const dimensionClass = this.onChangedimensionClass(ASSET_ALLOCATION_BOND);
        this.setState({
          dimensionClass,
        });
        if (dimensionClass.length) this.state.dimensionSelect.setSelect(dimensionClass[0].value);
      },
    };

    return (
      <div>
        <FirstHeaderC title='大类资产维度统计' />
        <AdvancedSearch {...searchProps} />
        <div style={{ marginTop: '20px' }}>
          <Spin spinning={this.props.loading == true}>
            <SecondHeaderC title='维度' />
            <div className={type == 1 ? myStyle.asset1 : myStyle.asset2}>
              <div>
                <ChartPie eChartsType={2} data={pieData} height='300px' />
              </div>
              <div>
                <TableC columns={columns} dataSource={dataSource} rowKey='dimension' hidePage={true} scroll={{ y: 334 }} />
              </div>
            </div>
          </Spin>
        </div>
      </div>
    );
  }
}
export default connect(({ assetAllocationM, loading, globalM }) => ({
  assetAllocationM,
  loading: loading.effects['assetAllocationM/queryDimensionData'],
  globalM,
}))(dimensionality);
